import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {Button, Space, Table, TreeSelect, Switch, message, Image} from 'antd';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable, {TableDropdown} from '@ant-design/pro-table';
import {PlusOutlined} from '@ant-design/icons';
import {getGoodsCategory, getGoodsLists, getGoodsTops, setGoodsPutAway} from "@/services/ant-design-pro/goods";
import {history} from 'umi';

const GoodsLists = () => {
  const [treeData,setTreeData] = useState([])
  const [topData,setTopData] = useState([])
  useEffect(()=>{
    getGoodsCategory().then(res => {
      setTreeData(res)
    })
  },[])

 useEffect(()=>{
    getGoodsTops().then(res => {
      res = res.data.map((item,index) =>{
        item.key = index
        item.tab = item.name+'（'+item.count+')'
        return item
      })
      setTopData(res)
    })
  },[])


  const [search, setSearch] = useState({status: 1, include: 'productattrvalue'})
  const actionRef = useRef<ActionType>();

  const columns: ProColumns = [
    {
      title: '商品ID',
      dataIndex: 'id',
      search: false,
      align: 'center',
      width: 100,
    },
    {
      title: '商品图',
      dataIndex: 'image',
      search: false,
      align: 'center',
      render: (_, record) => {
        return (
          <Image
            width={50}
            src={record.image}
          />
        );
      }
    },
    {
      title: '商品名称',
      dataIndex: 'product_name',
      search: false,
      align: 'center',
      width: 200,
    },
    {
      title: '商品售价',
      dataIndex: 'productattrvalue["ot_price"]',
      search: false,
      align: 'center',
      width: 100,
      render: (_, record) =>{

          return <span>{record?.productattrvalue?.ot_price ?? '未定义' }</span>
      }
    },
    {
      title: '库存',
      dataIndex: 'stock',
      search: false,
      align: 'center',
      width: 100,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      search: false,
      align: 'center',
      width: 100,
    },
    {
      title: '商品分类',
      dataIndex: 'top_id',
      hideInTable: true,
      search: true,
      width: 100,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <TreeSelect
              style={{width: '100%'}}
              fieldNames-={{ label: 'nickname', key: 'id', children: 'children' }}
              treeData={treeData}
              dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
              placeholder="请选择"
              {...fieldProps}
            />
          );
        }
        return defaultRender(_);
      }
    },
    {
      title: '商品搜索',
      dataIndex: 'search',
      search: true,
      hideInTable: true,
      renderFormItem: (_, {defaultRender}) => {
        return defaultRender(_);
      },
    },
    {
      title: '销量',
      dataIndex: 'sales',
      align: 'center',
      search: false,
      width: 100,
      sorter: (a, b) => a.containers - b.containers,
    },
    {
      title: '状态',
      dataIndex: 'status',
      search: false,
      align: 'center',
      valueType: 'select',
      width: 100,
      render: (_, record) =>
        <Switch
          checkedChildren="上架"
          unCheckedChildren="下架"
          defaultChecked={record.status}
          onChange={async (state) => {
            console.log(state);
            setGoodsPutAway({
              ids: record.id,
              status: state ? 1 : 0,
            }).then(() => {
              message.success('操作成功！')
              actionRef.current.reload();
            })
          }
          }
        />
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => history.push('/manageGoods/editGoods/3433')}
        >
          编辑
        </a>,
        <a href={record.url} target="_blank" rel="noopener noreferrer" key="view">
          查看
        </a>,
        <TableDropdown
          key="actionGroup"
          onSelect={() => action?.reload()}
          menus={[
            {key: 'copy', name: '复制'},
            {key: 'delete', name: '删除'},
          ]}
        />,
      ],
    },
  ];

  return (
      <PageContainer
        header={{
          title: '商品列表',
          breadcrumb: {},
        }}
        tabList={topData}
        onTabChange={(key) => {
          let item =  topData[key]
          let searchItem;
          switch (key){
            case '0':
            case '1':
              console.log(item);
            searchItem = {status:item.status}
              break;
            case '2':
            case '3':
         searchItem = {stock:item.stock}
              break;
            case '4':
           searchItem = {deleted:item.deleted}
              break;
          }
          setSearch({...searchItem, include: 'productattrvalue'})

          actionRef.current.reload();

        }}
      >
        <ProTable
          columns={columns}
          actionRef={actionRef}
          rowSelection={{
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          }}
          tableAlertRender={({selectedRowKeys, selectedRows, onCleanSelected}) => (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{marginLeft: 8}} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
            </Space>
          )}
/*          request={async (params) => {
            const data = await getGoodsCategory({...params});
            return {
              data
            }
          }}*/
          request={async (params = {}, sort, filter) => {
            return getGoodsLists({...sort, ...filter, ...params, ...search});
          }}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          pagination={{
            pageSize: 10,
            total:20
          }}
          dateFormatter="string"
          headerTitle=""
          toolBarRender={() => [
            <Button key="button" icon={<PlusOutlined/>} type="primary"
                    onClick={() => history.push('/manageGoods/addGoods')}>
              添加商品
            </Button>,
           /* <Button key="button" type="primary">
              商品采集
            </Button>*/
          ]}
        />
      </PageContainer>

  );
};

export default GoodsLists;
